<?php
/**
 * Created by PhpStorm.
 * User: aDaddy
 * Date: 2016/7/25
 * Time: 9:55
 */

namespace Model\ExamBundle\Model;
use Base\BaseModel;
use Model\ExamBundle\Setting\ExamSetting;

class ExamModel extends BaseModel{

    /*
     * 列表基本设置【通用模块必须开发】
     */
    public function listSettingDefault()
    {
        $settings = new ExamSetting($this->getDoctrine());
        return $settings->listConfig();
    }

    /*
     * 为后台获取所有文章分类【通用模块必须开发】
     */
    /**
     * @param array $params $param[textKey]=textKey , $param[conditions][table][field][eq|gt|lt...]=value , $param[orderBy][table][field]=DESC|ASC
     * @param int $offset
     * @param int $perPage
     * @return array
     */
    public function getAdminLists($params ,$offset = 0 , $perPage = 10)
    {
        $qb = $this->getQueryFromParam($params);
        $lists = $this->getAllResult($qb,$offset,$perPage);
        $total = $this->countAllResult($qb);

        return array(
            "total" => $total ? $total : 0,
            "data"  => $lists
        );
    }

    public function getExamOne($id)
    {
        $qb = $this->getQueryBuilder();
        $qb->select("*")->from("Exam");
        $qb->where("id = :id")->setParameter("id",$id);
        return $qb->execute()->fetch();
    }


    public function getByUserId($userId ,$offset = 0 , $perPage = 10)
    {
        $qb = $this->getQueryBuilder();
        $qb->select("Exam.*,count(ExamQuestion.questionId) as questionNum")->from("Exam");
        $qb->where("userId = :userId")->setParameter("userId",$userId);
        $qb->leftJoin("Exam","ExamQuestion","ExamQuestion","ExamQuestion.examId = Exam.id");
        $qb->groupBy(array("Exam.id"));
        $qb->orderBy("Exam.id","DESC");
        $qb->setFirstResult($offset);
        $qb->setMaxResults($perPage);
        return $qb->execute()->fetchAll();
    }


    public function get4Course($courseId , $userId  ,$offset = 0 , $perPage = 10)
    {
        //获取所有
        $allMyExam = $this->getByUserId($userId ,$offset  , $perPage );

        //筛选出已加入课程的
        $rep = $this->getDoctrine()->getRepository("ModelCourseBundle:CourseExam");
        $courseExam = $rep->findBy(array("courseId" => $courseId));

        $selectedExamIds = array();
        foreach ($courseExam as $item) {
            $selectedExamIds[] = $item->getExamId();
        }

        //从总数据中将选中的和没选中的分开
        $selectedData = array();
        $notSelectedData = array();
        foreach ($allMyExam as $oneExam) {
            if (in_array($oneExam["id"],$selectedExamIds)) {
                $selectedData[] = $oneExam;
            } else {
                $notSelectedData[] = $oneExam;
            }
        }

        return array(
            "selectedData"   => $selectedData,
            "notSelectedData"   => $notSelectedData,
        );

    }

    public function getQuestion4Exam($examId)
    {

        $examGroups = $this->getExamQuestionGroups($examId);
        $examGroups = array_merge(array(array("id"=>0,"title"=>"未分组")),$examGroups);
        foreach ($examGroups as &$group) {
            $group["questions"] = $this->getGroupQuestions($group["id"]);
        }
        return $examGroups;
    }

    public function getExamQuestionGroups($examId)
    {
        $qb = $this->getQueryBuilder();
        $qb->select("*")->from("ExamQuestionGroup");
        $qb->where("ExamId = :ExamId")->setParameter("ExamId",$examId);
        $qb->orderBy("orders","ASC");
        return $qb->execute()->fetchAll();
    }


    public function getExamQuestionChoices($questionId)
    {
        $qb = $this->getQueryBuilder();
        $qb->select("*")->from("Choice");
        $qb->where("QuestionId = :QuestionId")->setParameter("QuestionId",$questionId);
        $qb->orderBy("id","ASC");
        return $qb->execute()->fetchAll();
    }

    public function getGroupQuestions($groupId)
    {
        $qb = $this->getQueryBuilder();
        $qb->select("ExamQuestion.*,Question.title")->from("ExamQuestion");
        $qb->where("groups = :groups")->setParameter("groups",$groupId);
        $qb->leftJoin("ExamQuestion","Question","Question","ExamQuestion.questionId = Question.id");
        $qb->orderBy("orders","ASC");
        return $qb->execute()->fetchAll();
    }

    public function getGroupOne($id)
    {
        $qb = $this->getQueryBuilder();
        $qb->select("*")->from("ExamQuestionGroup");
        $qb->where("id = :id")->setParameter("id",$id);
        return $qb->execute()->fetch();
    }

    public function getGroupAside($id,$side,$checkExamId = "")
    {
        if (!$self = $this->getGroupOne($id)) {
            return false;
        } else {
            $selfOrders = $self["orders"];
        }
        if ($side > 0 ) {
            $cond = ">";
            $dir = "ASC";
        } else {
            $cond = "<";
            $dir = "DESC";
        }
        $qb = $this->getQueryBuilder();
        $qb->select("id")->from("ExamQuestionGroup");
        $qb->where("orders $cond :orders")->setParameter("orders",$selfOrders);
        if ($checkExamId) {
            $qb->andWhere("examId = :examId")->setParameter("examId",$checkExamId);
        }
        $qb->orderBy("orders","$dir");
        return $qb->execute()->fetch();
    }

    public function modGroupOrders($id,$action,$checkExamId = "")
    {
        $rep = $this->getDoctrine()->getRepository("ModelExamBundle:ExamQuestionGroup");
        $em = $this->getDoctrine()->getManager();
        $self = $rep->find($id);
        if (!$self) {
            return false;
        }

        switch ($action) {
            case "up":
                //升一位
                if (!$targetArray = $this->getGroupAside($id,-1,$checkExamId)) {
                    return false;
                }
                $target = $rep->find($targetArray["id"]);
                $selfOrders = $self->getOrders();
                $targetOrders = $target->getOrders();
                $self->setOrders($targetOrders);
                $target->setOrders($selfOrders);
                $em->persist($target);
                $em->persist($self);
                break;
            case "down":
                //降一位
                if (!$targetArray = $this->getGroupAside($id,1,$checkExamId)) {
                    return false;
                }
                $target = $rep->find($targetArray["id"]);
                $selfOrders = $self->getOrders();
                $targetOrders = $target->getOrders();
                $self->setOrders($targetOrders);
                $target->setOrders($selfOrders);
                $em->persist($target);
                $em->persist($self);
                break;
            case "del":
                //删除一位
                $em->remove($self);
                $this->modExamQuestionGroup($checkExamId,$id,0);
                break;
            default:

        }
        $em->flush();

        return true;
    }

    public function modExamQuestionGroup( $examId , $fromGroup , $toGroup )
    {
        $qb = $this->getQueryBuilder();
        $qb->update("ExamQuestion");
        $qb->set("groups",":toGroups")->setParameter("toGroups",$toGroup);
        $qb->where("groups = :groups")->setParameter("groups",$fromGroup);
        $qb->andWhere("examId = :examId")->setParameter("examId",$examId);
        return $qb->execute();
    }




    public function getExamQuestionOne($id)
    {
        $qb = $this->getQueryBuilder();
        $qb->select("*")->from("ExamQuestion");
        $qb->where("id = :id")->setParameter("id",$id);
        return $qb->execute()->fetch();
    }

    public function getExamQuestionAside($id,$side,$checkExamId = "")
    {
        if (!$self = $this->getExamQuestionOne($id)) {
            return false;
        } else {
            $selfOrders = $self["orders"];
        }
        if ($side > 0 ) {
            $cond = ">";
            $dir = "ASC";
        } else {
            $cond = "<";
            $dir = "DESC";
        }
        $qb = $this->getQueryBuilder();
        $qb->select("id")->from("ExamQuestion");
        $qb->where("orders $cond :orders")->setParameter("orders",$selfOrders);
        if ($checkExamId) {
            $qb->andWhere("examId = :examId")->setParameter("examId",$checkExamId);
        }
        $qb->orderBy("orders","$dir");
        return $qb->execute()->fetch();
    }

    public function modExamQuestionOrders($id,$action,$checkExamId = "")
    {
        $rep = $this->getDoctrine()->getRepository("ModelExamBundle:ExamQuestion");
        $em = $this->getDoctrine()->getManager();
        $self = $rep->find($id);
        if (!$self) {
            return false;
        }


        switch ($action) {
            case "up":
                //升一位
                if (!$targetArray = $this->getExamQuestionAside($id,-1,$checkExamId)) {
                    return false;
                }
                $target = $rep->find($targetArray["id"]);
                $selfOrders = $self->getOrders();
                $targetOrders = $target->getOrders();
                $self->setOrders($targetOrders);
                $target->setOrders($selfOrders);
                $em->persist($target);
                $em->persist($self);
                break;
            case "down":
                //降一位
                if (!$targetArray = $this->getExamQuestionAside($id,1,$checkExamId)) {
                    return false;
                }
                $target = $rep->find($targetArray["id"]);
                $selfOrders = $self->getOrders();
                $targetOrders = $target->getOrders();
                $self->setOrders($targetOrders);
                $target->setOrders($selfOrders);
                $em->persist($target);
                $em->persist($self);
                break;
            case "del":
                //删除一位
                $em->remove($self);
                break;
            default:

        }
        $em->flush();

        return true;
    }


    public function getFromCourse4TestOrExam($courseId)
    {

        //筛选出已加入课程的
        $rep = $this->getDoctrine()->getRepository("ModelCourseBundle:CourseExam");
        $courseExam = $rep->findBy(array("courseId" => $courseId));

        $selectedExamIds = array();
        foreach ($courseExam as $item) {
            $selectedExamIds[] = $item->getExamId();
        }




        $qb = $this->getQueryBuilder();
        $qb->select("Exam.*")->from("CourseExam");
        $qb->leftJoin("CourseExam","Exam","Exam","Exam.id = CourseExam.examId");
        $qb->where("courseId = :courseId")->setParameter("courseId",$courseId);
        $allExam = $qb->execute()->fetchAll();
        return $allExam;
    }

    //***************************考试数据准备******************************************
    public function getTotalData4Exam($examId,$isPractise = 1)
    {
        if (!$exam = $this->getExamOne($examId)) {
            return false;
        }
        if (!$groups = $this->getExamQuestionGroups($examId)) {
            $groups = array(
                array(
                    "id"    => 0,
                    "title" => "题目列表："
                )
            );
        }

        $questionNum = 1;

        $Main = array();
        $Main["examInfo"] = $exam;
        foreach ($groups as $key => $oneGroup) {
            $Main["questionGroups"][$key]["groupInfo"] = $oneGroup;
            //取出所有题目并进行处理
            $questions = $this->getGroupQuestions($oneGroup["id"]);
            foreach ($questions as $k => $oneQuestion) {
                $oneQuestion["questionNum"] = $questionNum;
                $questionNum ++;
                $Main["questionGroups"][$key]["groupQuestions"][$k]["questionInfo"] = $oneQuestion;

                $questionId = $oneQuestion["id"];
                $choice = $this->getExamQuestionChoices($questionId);
                if (!$isPractise) {
                    //考试环境需要把数据中是否是正确答案的数据去掉
                    foreach ($choice as &$c) {
                        unset($c["isAnswer"]);
                    }
                }


                $Main["questionGroups"][$key]["groupQuestions"][$k]["choices"] = $choice;
            }
        }
        return $Main;
    }

}